﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace AutoBlogger.Tool
{
    internal class YouDao
    {
        public string Url { get; private set; }
        public string RealUrl { get; private set; }
        public string TranslatedResult { get; private set; }
        WebClient wClient = null;

        internal YouDao(string url)
        {
            Url = url;

            WebHeaderCollection webHeaderList = new WebHeaderCollection();
            webHeaderList["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            webHeaderList["Accept-Charset"] = "GBK,utf-8;q=0.7,*;q=0.3";
            webHeaderList["Accept-Encoding"] = "gzip,deflate,sdch";
            webHeaderList["Accept-Language"] = "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4";
            webHeaderList["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1290.1 Safari/537.13";
            webHeaderList["Cookie"] = "OUTFOX_SEARCH_USER_ID=1211142478@119.40.37.156; bdshare_firstime=1353820211267; __ntes__test__cookies=1353820987520; _ntes_nnid=6f891d6857ff3d1416905d1d52122e45,1353820896605";

            wClient = new WebClient();
            //if (!string.IsNullOrEmpty(proxy))
            //{
            //    wClient.Proxy = new WebProxy(proxy);
            //}
            wClient.Encoding = Encoding.UTF8;
            wClient.Headers = webHeaderList;

            string realUrl = getRealUrl(url);

            TranslatedResult = getResponse(realUrl);
        }

        private string getRealUrl(string url)
        {
            string response = getResponse(url);
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(response);
            var iFrame = doc.GetElementbyId("youdaotranslateIframe");
            if (iFrame != null && iFrame.Attributes["src"] != null)
            {
                return iFrame.Attributes["src"].Value;
            }
            return string.Empty;
        }

        internal string getResponse(string url)
        {
            byte[] resultData = wClient.DownloadData(url);
            string resultStr = NetClient.UnZipHtml(resultData);

            return resultStr;
        }
    }
}
